import React, { useState, useCallback, useRef, useEffect } from 'react';
import { SpinLoading, InfiniteScroll } from 'antd-mobile';
import './VirtualList.scss';

interface ListItem {
  id: number;
  title: string;
  description: string;
  image?: string;
  tag?: string;
  date?: string;
  views?: number;
}

interface VirtualListProps {
  data: ListItem[];
  loading?: boolean;
  hasMore?: boolean;
  onLoadMore?: () => void;
  onItemClick?: (item: ListItem) => void;
  itemHeight?: number;
  containerHeight?: number;
}

const VirtualList: React.FC<VirtualListProps> = ({
  data,
  loading = false,
  hasMore = true,
  onLoadMore,
  onItemClick,
  itemHeight = 80,
  containerHeight = 400
}) => {
  const [visibleRange, setVisibleRange] = useState({ start: 0, end: 10 });
  const containerRef = useRef<HTMLDivElement>(null);

  // 计算可见区域的项目
  const calculateVisibleRange = useCallback(() => {
    if (!containerRef.current) return;

    const container = containerRef.current;
    const scrollTop = container.scrollTop;
    const containerHeight = container.clientHeight;

    const start = Math.floor(scrollTop / itemHeight);
    const end = Math.min(start + Math.ceil(containerHeight / itemHeight) + 2, data.length);

    setVisibleRange({ start, end });
  }, [data.length, itemHeight]);

  // 滚动事件处理
  const handleScroll = useCallback(() => {
    calculateVisibleRange();
  }, [calculateVisibleRange]);

  // 监听滚动事件
  useEffect(() => {
    const container = containerRef.current;
    if (container) {
      container.addEventListener('scroll', handleScroll);
      return () => container.removeEventListener('scroll', handleScroll);
    }
  }, [handleScroll]);

  // 初始计算可见区域
  useEffect(() => {
    calculateVisibleRange();
  }, [calculateVisibleRange]);

  // 处理加载更多
  const handleLoadMore = async (_isRetry: boolean) => {
    if (onLoadMore) {
      onLoadMore();
    }
  };

  // 渲染列表项
  const renderListItem = (item: ListItem, index: number) => {
    const style = {
      height: `${itemHeight}px`,
      transform: `translateY(${index * itemHeight}px)`,
    };

    return (
      <div
        key={item.id}
        className="virtual-list-item"
        style={style}
        onClick={() => onItemClick?.(item)}
      >
        <div className="item-content">
          {item.image && (
            <div className="item-image">
              <img src={item.image} alt={item.title} />
            </div>
          )}
          <div className="item-info">
            <h3 className="item-title">{item.title}</h3>
            <p className="item-description">{item.description}</p>
            <div className="item-meta">
              {item.tag && <span className="item-tag">{item.tag}</span>}
              {item.date && <span className="item-date">{item.date}</span>}
              {item.views && <span className="item-views">👁 {item.views}</span>}
            </div>
          </div>
        </div>
      </div>
    );
  };

  // 渲染可见的项目
  const visibleItems = data.slice(visibleRange.start, visibleRange.end);

  return (
    <div className="virtual-list-container">
      <div
        ref={containerRef}
        className="virtual-list-wrapper"
        style={{ height: containerHeight }}
      >
        <div
          className="virtual-list-content"
          style={{ height: `${data.length * itemHeight}px` }}
        >
          {visibleItems.map((item, index) => 
            renderListItem(item, visibleRange.start + index)
          )}
        </div>
      </div>
      
      {/* 加载更多 */}
      {hasMore && (
        <InfiniteScroll
          loadMore={handleLoadMore}
          hasMore={hasMore}
        >
          {loading && (
            <div className="loading-container">
              <SpinLoading />
              <span>加载中...</span>
            </div>
          )}
        </InfiniteScroll>
      )}
    </div>
  );
};

export default VirtualList;
